/**@file     spi.c
 * @brief
 * 
 * @author SealedGhost
 */
 
 
 
 
#include "spi.h"

#include "stm32f10x_gpio.h"
#include "stm32f10x_spi.h"
#include "stm32f10x.h"


#include "debug.h"


/** @addtogroup SPI
 *   
 *   @{
 */



/**@brief spi初始化
 *
 * @note  从机模式
 *        SCK     PA.5
 *        MISO    PA.6
 *        MOSI    PA.7
 *        NSS     PA.4 
 */
void initSpi1()
{
	GPIO_InitTypeDef gpioConfig;
	SPI_InitTypeDef  spiConfig;

	
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_SPI1, ENABLE);
	
	
	gpioConfig.GPIO_Speed			= GPIO_Speed_50MHz;
	
	gpioConfig.GPIO_Mode			= GPIO_Mode_AF_PP;
	gpioConfig.GPIO_Pin				= GPIO_Pin_5 | GPIO_Pin_6 | GPIO_Pin_7 ;
	GPIO_Init(GPIOA, &gpioConfig);
	
	GPIO_SetBits(GPIOA, GPIO_Pin_5 | GPIO_Pin_6 | GPIO_Pin_7 );
	
	
	spiConfig.SPI_BaudRatePrescaler		= SPI_BaudRatePrescaler_256;
	spiConfig.SPI_CPHA					= SPI_CPHA_2Edge;
	spiConfig.SPI_CPOL					= SPI_CPOL_High;
	spiConfig.SPI_CRCPolynomial			= 7;
	spiConfig.SPI_DataSize				= SPI_DataSize_8b;
	spiConfig.SPI_Direction				= SPI_Direction_1Line_Rx;
	spiConfig.SPI_FirstBit				= SPI_FirstBit_MSB;
	spiConfig.SPI_Mode					= SPI_Mode_Slave;
	spiConfig.SPI_NSS 					= SPI_NSS_Soft;
	
	SPI_Init(SPI1, &spiConfig);
	
	
	SPI_I2S_ITConfig(SPI1, SPI_I2S_IT_RXNE, ENABLE);
	

	
	SPI_Cmd(SPI1, ENABLE);
}



/**@brief spi初始化
 *
 * @note  主机模式
 *        SCK     PB.13
 *        MISO    PB.14
 *        MOSI    PB.15
 *        NSS     PB.12 
 */
void initSpi2(void)
{
	GPIO_InitTypeDef gpioConfig;
	SPI_InitTypeDef  spiConfig;
	
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_SPI2,  ENABLE);
	
	gpioConfig.GPIO_Speed			= GPIO_Speed_50MHz;
	
	gpioConfig.GPIO_Mode			= GPIO_Mode_AF_PP;
	gpioConfig.GPIO_Pin				= GPIO_Pin_13 | GPIO_Pin_14 | GPIO_Pin_15;
	GPIO_Init(GPIOB, &gpioConfig);
	
	GPIO_SetBits(GPIOB, GPIO_Pin_13 | GPIO_Pin_14 | GPIO_Pin_15);
	
	
	spiConfig.SPI_BaudRatePrescaler		= SPI_BaudRatePrescaler_256;
	spiConfig.SPI_CPHA					= SPI_CPHA_2Edge;
	spiConfig.SPI_CPOL					= SPI_CPOL_High;
	spiConfig.SPI_CRCPolynomial			= 7;
	spiConfig.SPI_DataSize				= SPI_DataSize_8b;
	spiConfig.SPI_Direction				= SPI_Direction_1Line_Tx;
	spiConfig.SPI_FirstBit				= SPI_FirstBit_MSB;
	spiConfig.SPI_Mode					= SPI_Mode_Master;
	spiConfig.SPI_NSS 					= SPI_NSS_Soft;
	
	SPI_Init(SPI2, &spiConfig);
	

	
	SPI_Cmd(SPI2, ENABLE);	
}




void SPI1_IRQHandler(void)
{
	uint16_t recData  = 0;
	if(SPI_I2S_GetITStatus(SPI1, SPI_I2S_IT_RXNE) != RESET)
	{
		recData  = SPI_I2S_ReceiveData(SPI1);
		Debug("SPI rev %x", recData);
	}
}



void sendByteBySpi(SPI_TypeDef* spi, uint16_t val)
{
	while((spi->SR & SPI_I2S_FLAG_TXE) == 0);
	SPI_I2S_SendData(spi, val);
}



void sendBytesBySpi(SPI_TypeDef* spi, uint16_t* buf, size_t size)
{
	while(size--)
	{
		while((spi->SR & SPI_I2S_FLAG_TXE) == 0);
		SPI_I2S_SendData(spi, *buf++);
	}
}




/** @} */


